package com.incar.chuxing.activity.certification;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.idcardquality.IDcardQualityProcess;
import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.sdk.model.IDCardResult;
import com.baidu.ocr.sdk.model.OcrRequestParams;
import com.baidu.ocr.sdk.model.OcrResponseResult;
import com.baidu.ocr.ui.camera.CameraNativeHelper;
import com.baidu.ocr.ui.camera.CameraThreadPool;
import com.baidu.ocr.ui.camera.CameraView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.incar.chuxing.R;
import com.incar.chuxing.activity.MainActivity;
import com.incar.chuxing.api.ApiStore;
import com.incar.chuxing.api.UrlContainer;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.bean.CommitCardInforBean;
import com.incar.chuxing.bean.DrvingBean;
import com.incar.chuxing.bean.IdCardFrontBean;
import com.incar.chuxing.bean.QualificationBean;
import com.incar.chuxing.bean.UploadImageBaidu;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.EditTextMonitorUtils;
import com.incar.chuxing.utils.ImageLoader;
import com.incar.chuxing.utils.Logger;
import com.incar.chuxing.utils.SDCardUtils;
import com.incar.chuxing.utils.SPKey;
import com.incar.chuxing.utils.SPUtils;
import com.incar.chuxing.utils.ToastUtils;
import com.incar.chuxing.utils.bos.UploadPicUtil;
import com.incar.chuxing.utils.ocrlicense.FileUtil;
import com.incar.chuxing.utils.policecertify.APIService;
import com.incar.chuxing.utils.policecertify.FaceException;
import com.incar.chuxing.utils.policecertify.LivenessVsIdcardResult;
import com.incar.chuxing.utils.policecertify.PoliceOnResultListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


/**
 * 身份认证页面
 */
public class CertifyCardActivity extends BaseActivity {

    @BindView(R.id.tv_next)
    TextView tv_next;
    @BindView(R.id.tv_forgetCard)
    TextView tv_forgetCard;
    @BindView(R.id.edt_idName)
    EditText edt_idName;
    @BindView(R.id.edt_idNum)
    EditText edt_idNum;
    @BindView(R.id.title_back)
    ImageView title_back;
    @BindView(R.id.title_more)
    ImageView title_more;
    @BindView(R.id.title_tv_more)
    TextView title_tv_more;

    @BindView(R.id.iv_drive_hou)
    ImageView iv_drive_hou;
    @BindView(R.id.iv_idcard_versa)
    ImageView iv_idcard_versa;
    @BindView(R.id.iv_selfphoto)
    ImageView iv_selfphoto;
    @BindView(R.id.iv_idcard_front)
    ImageView iv_idcard_front;
    @BindView(R.id.iv_drive_qian)
    ImageView ivDriveQian;
    @BindView(R.id.iv_user_depositverfiy_leftpro)
    ImageView ivUserDepositverfiyLeftpro;


    private Context mContext = this;
    private int submitType;
    private File originalFile;
    private File compressFile;
    private ArrayList<String> pics = new ArrayList<>();
    private String[] picTokenArray = new String[]{"", "", "", "", ""};
    private String[] picKeyArray = new String[]{"", "", "", "", ""};
    private boolean flag, flag0, flag1, flag2, flag3, flag4;
    private boolean cameraFlag;
    private String depositCarStatus;
    private String ZhiMaStatus;
    private String jishenStatus;
    private String licenseStatus;
    private int NativeIdCardFront;//idCard次数
    private int NativeIdCardBack;//
    private String filePath;
    private String ocrStatus = "0";
    private String policeDegree = "";
    private String name;
    private String num;
    private String idCardFront, idCardBack, drivingCard;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case 1:
                    showLoadingDialog();
                    break;
                case 2:
                    //成功压缩
                    String pathName = msg.getData().getString("compressPath");
                    pics.add(pathName);
                    //上传图片
                    compressFile = new File(pathName);
                    uploadImage(compressFile);
                    break;
                case 3:
                    //压缩失败
                    dismissLoadingDialog();
                    picKeyArray[submitType] = "";
                    ToastUtils.makeText(mContext, "图片上传失败，请重试", ToastUtils.LENGTH_SHORT).show();
                    break;
                case 4: //上传成功
                    dismissLoadingDialog();

                    if (submitType == 0) {
                        ImageLoader.getInstance().displayImageFitCenter(mContext, compressFile, iv_idcard_front);
                        flag0 = true;
                    } else if (submitType == 1) {
                        ImageLoader.getInstance().displayImageFitCenter(mContext, compressFile, iv_idcard_versa);
                        flag1 = true;
                    } else if (submitType == 2) {
                        ImageLoader.getInstance().displayImageFitCenter(mContext, compressFile, iv_selfphoto);
                        flag2 = true;
                    } else if (submitType == 3) {
                        ImageLoader.getInstance().displayImageFitCenter(mContext, compressFile, ivDriveQian);
                        flag3 = true;
                    } else if (submitType == 4) {
                        ImageLoader.getInstance().displayImageFitCenter(mContext, compressFile, iv_drive_hou);
                        flag4 = true;
                    }
                    if (flag0 && flag1 && flag2 && flag3 & flag4) {
                        flag = true;
                        checkInfo();
                    }
                    break;
                case 5:
                    //上传失败
                    dismissLoadingDialog();
                    picKeyArray[submitType] = "";
                    ToastUtils.makeText(mContext, msg.getData().getString("failReason"), ToastUtils.LENGTH_SHORT).show();
                    break;
                case 6:
                    //上传取消
                    dismissLoadingDialog();
                    picKeyArray[submitType] = "";
                    ToastUtils.makeText(mContext, "图片上传取消", ToastUtils.LENGTH_SHORT).show();
                    break;
            }
            super.handleMessage(msg);
        }
    };
    private File outputFile_drive;
    private File outputFile_idCard;
    private File outputFile_self;
    private int intentFrom;
    private boolean intentTo = false;
    private String fromType;

    @Override
    public int getLayoutId() {
        return R.layout.activity_verify_card;
    }

    @Override
    public void initView() {
        fromType = getIntent().getStringExtra("fromType");
        initTitleData();
        checkInfo();
        checkCarUserStatus();
        //初始化OCR单利
        initAccessToken();
        //  初始化本地质量控制模型,释放代码在onDestory中
        //  调用身份证扫描必须加上 intent.putExtra(CameraActivity.KEY_NATIVE_MANUAL, true); 关闭自动初始化和释放本地模型
        CameraNativeHelper.init(this, OCR.getInstance(this).getLicense(),
                new CameraNativeHelper.CameraNativeInitCallback() {
                    @Override
                    public void onError(int errorCode, Throwable e) {
                        String msg;
                        switch (errorCode) {
                            case CameraView.NATIVE_SOLOAD_FAIL:
                                msg = "加载so失败，请确保apk中存在ui部分的so";
                                break;
                            case CameraView.NATIVE_AUTH_FAIL:
                                msg = "授权本地质量控制token获取失败";
                                break;
                            case CameraView.NATIVE_INIT_FAIL:
                                msg = "本地质量控制";
                                break;
                            default:
                                msg = String.valueOf(errorCode);
                        }
                        Logger.d("ORCINIT", msg + "");
                    }
                });
    }

    //初始化OCR单利
    private void initAccessToken() {
        OCR.getInstance(this).initAccessToken(new com.baidu.ocr.sdk.OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                String token = accessToken.getAccessToken();
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                Logger.d("OCRTOKEN", error.getMessage());
            }
        }, getApplicationContext());
    }

    @OnClick({R.id.title_tv_more, R.id.iv_idcard_front, R.id.iv_idcard_versa, R.id.iv_selfphoto, R.id.iv_drive_hou, R.id.iv_drive_qian, R.id.tv_next, R.id.tv_forgetCard, R.id.title_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                AppManager.getAppManager().finishActivity();
                break;
            case R.id.title_tv_more:
                startActivity(new Intent(mContext, MainActivity.class));
                AppManager.getAppManager().finishActivity();
                break;
            case R.id.iv_idcard_front:
                submitType = 0;
                if (NativeIdCardFront < 2) {
                    NativeIdCardFront++;
                    Intent intent_front = new Intent(mContext, CameraActivity.class);
                    intent_front.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                            FileUtil.getSaveFile(mContext).getAbsolutePath());
                    intent_front.putExtra(CameraActivity.KEY_NATIVE_TOKEN,
                            OCR.getInstance(this).getLicense());
                    intent_front.putExtra(CameraActivity.KEY_NATIVE_ENABLE,
                            true);
                    // KEY_NATIVE_MANUAL设置了之后CameraActivity中不再自动初始化和释放模型
                    // 请手动使用CameraNativeHelper初始化和释放模型
                    // 推荐这样做，可以避免一些activity切换导致的不必要的异常
                    intent_front.putExtra(CameraActivity.KEY_NATIVE_MANUAL, true);
                    intent_front.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
                    intent_front.putExtra("submitType", submitType);
                    startActivityForResult(intent_front, submitType);
                } else {
                    Intent intent = new Intent(mContext, CameraActivity.class);
                    intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                            FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                    intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
                    startActivityForResult(intent, submitType);
                }
                break;
            case R.id.iv_idcard_versa:
                submitType = 1;
                if (NativeIdCardBack < 2) {
                    NativeIdCardBack++;
                    Intent intent_rear = new Intent(mContext, CameraActivity.class);
                    intent_rear.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                            FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                    intent_rear.putExtra(CameraActivity.KEY_NATIVE_TOKEN,
                            OCR.getInstance(this).getLicense());
                    intent_rear.putExtra(CameraActivity.KEY_NATIVE_ENABLE,
                            true);
                    // KEY_NATIVE_MANUAL设置了之后CameraActivity中不再自动初始化和释放模型
                    // 请手动使用CameraNativeHelper初始化和释放模型
                    // 推荐这样做，可以避免一些activity切换导致的不必要的异常
                    intent_rear.putExtra(CameraActivity.KEY_NATIVE_MANUAL,
                            true);
                    intent_rear.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_BACK);
                    intent_rear.putExtra("submitType", submitType);
                    startActivityForResult(intent_rear, submitType);
                } else {
                    Intent intent = new Intent(mContext, CameraActivity.class);
                    intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                            FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                    intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_BACK);
                    startActivityForResult(intent, submitType);
                }
                break;
            case R.id.iv_selfphoto:
                submitType = 2;
                Intent intent_self = new Intent(mContext, CameraActivity.class);
                intent_self.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveZiPaiFile(getApplication()).getAbsolutePath());
                intent_self.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                        CameraActivity.CONTENT_TYPE_GENERAL);
                intent_self.putExtra("submitType", submitType);
                startActivityForResult(intent_self, submitType);
                break;
            case R.id.iv_drive_qian:
                submitType = 3;
                Intent intent_drive0 = new Intent(mContext, CameraActivity.class);
                intent_drive0.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent_drive0.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                        CameraActivity.CONTENT_TYPE_BANK_CARD);
                intent_drive0.putExtra("submitType", submitType);
                startActivityForResult(intent_drive0, submitType);
                break;
            case R.id.iv_drive_hou:
                submitType = 4;
                Intent intent_drive1 = new Intent(mContext, CameraActivity.class);
                intent_drive1.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent_drive1.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                        CameraActivity.CONTENT_TYPE_BANK_CARD);
                intent_drive1.putExtra("submitType", submitType);
                startActivityForResult(intent_drive1, submitType);
                break;
            case R.id.tv_forgetCard:
                startActivity(new Intent(mContext, CertifyCardRemindActivity.class));
                break;
            case R.id.tv_next:
                if (picKeyArray[0].equals("")) {
                    ToastUtils.makeText(mContext, getString(R.string.idcard_font), ToastUtils.LENGTH_SHORT).show();
                } else if (picKeyArray[1].equals("")) {
                    ToastUtils.makeText(mContext, getString(R.string.idcard_versa), ToastUtils.LENGTH_SHORT).show();
                } else if (picKeyArray[2].equals("")) {
                    ToastUtils.makeText(mContext, getString(R.string.selfphoto), ToastUtils.LENGTH_SHORT).show();
                } else if (picKeyArray[3].equals("")) {
                    ToastUtils.makeText(mContext, getString(R.string.drivecard), ToastUtils.LENGTH_SHORT).show();
                } else if (picKeyArray[4].equals("")) {
                    ToastUtils.makeText(mContext, getString(R.string.drivecardfuben), ToastUtils.LENGTH_SHORT).show();
                } else {
                    showLoadingDialog();
                    name = edt_idName.getText().toString();
                    num = edt_idNum.getText().toString();
                    if (name.equals(SPUtils.getInstance(mContext).getStringValue(SPKey.IDCARD_NAME))
                            && name.equals(SPUtils.getInstance(mContext).getStringValue(SPKey.DRIVING_NAME))
                            && num.equals(SPUtils.getInstance(mContext).getStringValue(SPKey.IDCARD_NUM))) {
                        ocrStatus = "1";
                    }
                    String zipai = FileUtil.getSaveZiPaiFile(getApplication()).getAbsolutePath();
                    policeVerify(zipai);
                }
                break;
        }
    }

    private void confirmUserInfor() {
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).confirmUserInfor(((MyApplication) getApplication()).getRequestFieldMap(),
                edt_idName.getText().toString(), edt_idNum.getText().toString(), picKeyArray[0], picKeyArray[1], picKeyArray[2], picKeyArray[3], picKeyArray[4], ocrStatus, policeDegree, idCardFront, idCardBack, drivingCard).enqueue(new Callback<CommitCardInforBean>() {
            @Override
            public void onResponse(Call<CommitCardInforBean> call, Response<CommitCardInforBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        dismissLoadingDialog();

                        SPUtils.getInstance(mContext).putStringValue(SPKey.REAL_NAME_STATUS, response.body().getAttachment().getIdentityStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.DEPOSIT_CAR_STATUS, response.body().getAttachment().getDepositStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.LICENSE_CAR_STATUS, response.body().getAttachment().getLicenseStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.JISHEN_STATUS, response.body().getAttachment().getStatus() + "");
                        jishenStatus = response.body().getAttachment().getStatus() + "";
                        depositCarStatus = response.body().getAttachment().getDepositStatus() + "";
                        licenseStatus = response.body().getAttachment().getLicenseStatus() + "";

                        if (!intentTo) {
                            intentTo = true;
                            if ("18".equals(jishenStatus) || "13".equals(licenseStatus)) {
                                if (intentFrom == 2) {
                                    startActivity(new Intent(mContext, MainActivity.class));
                                } else {
                                    Intent intent = new Intent(mContext, CertifyCardFinishActivity.class);
                                    intent.putExtra("fromType", fromType);
                                    startActivity(intent);
                                }
                            } else {
                                Intent intent = new Intent(mContext, CertifyCardInActivity.class);
                                intent.putExtra("fromType", fromType);
                                startActivity(intent);
                            }
                            AppManager.getAppManager().finishActivity();
                        }
                    } else {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CommitCardInforBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    private void recIDCard(String idCardSide, String filePath) {
        IDCardParams param = new IDCardParams();
        param.setImageFile(new File(filePath));
        // 设置身份证正反面
        param.setIdCardSide(idCardSide);
        // 设置方向检测
        param.setDetectDirection(true);
        // 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
        param.setImageQuality(20);

        OCR.getInstance(this).recognizeIDCard(param, new OnResultListener<IDCardResult>() {
            @Override
            public void onResult(IDCardResult result) {
                Logger.d("OCRJSON", result.getJsonRes());
                String ocr = result.getJsonRes();
                if (idCardSide.equals(IDCardParams.ID_CARD_SIDE_BACK)) {
                    idCardBack = ocr + "";
                } else {
                    idCardFront = ocr + "";
                    Gson gson = new Gson();
                    String name = gson.fromJson(ocr, IdCardFrontBean.class).getWords_result().get姓名().getWords();
                    String num = gson.fromJson(ocr, IdCardFrontBean.class).getWords_result().get公民身份号码().getWords();
                    SPUtils.getInstance(mContext).putStringValue(SPKey.IDCARD_NAME, name);
                    SPUtils.getInstance(mContext).putStringValue(SPKey.IDCARD_NUM, num);
                }
            }

            @Override
            public void onError(OCRError error) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
                Logger.d("IDCARD_FAIL", error.getMessage());
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == submitType) {   //获得图片后
            if (resultCode == Activity.RESULT_OK) {
                if (data != null) {
                    if (submitType == 3) {
                        drivingCard = data.getStringExtra("DRIVING_JSON") + "";
                    }
                    String contentType = data.getStringExtra(CameraActivity.KEY_CONTENT_TYPE);
                    if (!TextUtils.isEmpty(contentType)) {
                        if (contentType.equals(CameraActivity.CONTENT_TYPE_GENERAL)) {
                            filePath = FileUtil.getSaveZiPaiFile(getApplicationContext()).getAbsolutePath();
                        } else {
                            filePath = FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath();
                        }
                        if (CameraActivity.CONTENT_TYPE_ID_CARD_FRONT.equals(contentType)) {
                            recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath);
                        } else if (CameraActivity.CONTENT_TYPE_ID_CARD_BACK.equals(contentType)) {
                            recIDCard(IDCardParams.ID_CARD_SIDE_BACK, filePath);//身份证反面不用识别
                        }
                        originalFile = new File(filePath);
                        Luban.with(mContext)
                                .load(originalFile)  //传入要压缩的图片
                                .setCompressListener(new OnCompressListener() {
                                    @Override
                                    public void onStart() {
                                        Message message = new Message();
                                        message.arg1 = 1;
                                        Bundle b = new Bundle();
                                        b.putString("originalPath", filePath);
                                        message.setData(b);
                                        handler.sendMessage(message);
                                    }

                                    @Override
                                    public void onSuccess(File file) {
                                        Message message = new Message();
                                        message.arg1 = 2;
                                        Bundle b = new Bundle();
                                        Logger.d("rename1", file.getAbsolutePath());
                                        File newFile = new File(file.getParent() + File.separator + SDCardUtils.createFileName(((MyApplication) getApplication()).getUid()) + ".jpg");
                                        file.renameTo(newFile);
                                        Logger.d("rename2", newFile.getAbsolutePath());
                                        b.putString("compressPath", newFile.getAbsolutePath());
                                        message.setData(b);
                                        handler.sendMessage(message);
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        Message message = new Message();
                                        message.arg1 = 3;
                                        handler.sendMessage(message);
                                    }
                                }).launch();    //启动压缩

                    } else {
                        return;
                    }
                }
            }
        }
    }

    /*
    * Java文件操作 获取不带扩展名的文件名
    */
    public String getFileNameNoEx(File nameFile) {
        String filename = nameFile.getName();
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }

    private void uploadImage(final File picFile) {
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).uploadImageBaidu(((MyApplication) getApplication()).getRequestFieldMap(), "stsToken", "upload").enqueue(new Callback<UploadImageBaidu>() {
            @Override
            public void onResponse(Call<UploadImageBaidu> call, Response<UploadImageBaidu> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        picTokenArray[submitType] = response.body().getAttachment().getStsToken();
                        picKeyArray[submitType] = getFileNameNoEx(picFile);
                        UploadPicUtil.getInstance().uploadPicToBos(picFile, response.body().getAttachment().getAk(),
                                response.body().getAttachment().getSk(), response.body().getAttachment().getBucketName(),
                                response.body().getAttachment().getStsToken(),
                                response.body().getAttachment().getBucketName(),
                                picKeyArray[submitType], new UploadPicUtil.OnFinishListener() {
                                    @Override
                                    public void onSuccess() {
                                        Message message = new Message();
                                        message.arg1 = 4;
                                        Bundle b = new Bundle();
                                        message.setData(b);
                                        handler.sendMessage(message);
                                    }

                                    @Override
                                    public void onFailure(String failReason) {
                                        Message message = new Message();
                                        message.arg1 = 5;
                                        Bundle b = new Bundle();
                                        b.putString("failReason", failReason);
                                        message.setData(b);
                                        handler.sendMessage(message);
                                    }
                                });

                    } else {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();

                }
            }

            @Override
            public void onFailure(Call<UploadImageBaidu> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }


    private void initTitleData() {
        title_back.setImageResource(R.drawable.icon_return_back);
        title_more.setVisibility(View.GONE);
        depositCarStatus = SPUtils.getInstance(mContext).getStringValue(SPKey.DEPOSIT_CAR_STATUS);
        ZhiMaStatus = SPUtils.getInstance(mContext).getStringValue(SPKey.ZHIMA_STATUS);
        jishenStatus = SPUtils.getInstance(mContext).getStringValue(SPKey.JISHEN_STATUS);
        intentFrom = getIntent().getIntExtra("intentFrom", 1);
        //=1是从个人信息跳转过来，跳过按钮不显示
        if (intentFrom == 2) {
            title_tv_more.setVisibility(View.VISIBLE);
            title_tv_more.setText("跳过");
        }
        if ("1".equals(depositCarStatus) || "1".equals(ZhiMaStatus) || "2".equals(depositCarStatus)) {
            ivUserDepositverfiyLeftpro.setImageResource(R.drawable.user_verfiy_leftpro);
        } else {
            ivUserDepositverfiyLeftpro.setImageResource(R.drawable.user_unverfiy_leftpro);
        }
    }

    private void checkInfo() {
        new EditTextMonitorUtils().SetMonitorEditText(tv_next, flag, edt_idName, edt_idNum);
        if (!TextUtils.isEmpty(edt_idName.getText().toString()) && !TextUtils.isEmpty(edt_idNum.getText().toString()) && flag) {
            tv_next.setBackgroundResource(R.drawable.btn_bg);
            tv_next.setEnabled(true);
        } else {
            tv_next.setBackgroundResource(R.drawable.btn_gray_bg);
            tv_next.setEnabled(false);
        }
    }

    private void checkCarUserStatus() {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getUserStatus(((MyApplication) getApplication()).getRequestFieldMap()).enqueue(new Callback<QualificationBean>() {
            @Override
            public void onResponse(Call<QualificationBean> call, Response<QualificationBean> response) {
                dismissLoadingDialog();
                if (response.isSuccessful() && response.body() != null) {

                    if (response.body().getStatus() == 200) {

                        if ("1".equals(response.body().getAttachment().getUserZmInfo())) {
                            edt_idName.setText(response.body().getAttachment().getUserName());
                            edt_idNum.setText(response.body().getAttachment().getIdentityCarNum());
                            edt_idName.setFocusable(false);
                            edt_idNum.setFocusable(false);
                        } else {
                            edt_idName.setText(response.body().getAttachment().getUserName());
                            edt_idNum.setText(response.body().getAttachment().getIdentityCarNum());
                            edt_idName.setFocusable(true);
                            edt_idNum.setFocusable(true);
                        }

                        SPUtils.getInstance(mContext).putStringValue(SPKey.REAL_NAME_STATUS, response.body().getAttachment().getIdentityStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.LICENSE_CAR_STATUS, response.body().getAttachment().getLicenseStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.DEPOSIT_CAR_STATUS, response.body().getAttachment().getDepositStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.JISHEN_STATUS, response.body().getAttachment().getStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.ZHIMA_STATUS, response.body().getAttachment().getAuthorize() + "");

                        depositCarStatus = response.body().getAttachment().getDepositStatus() + "";
                        ZhiMaStatus = response.body().getAttachment().getAuthorize() + "";
                        if ("1".equals(depositCarStatus) || "1".equals(ZhiMaStatus) || "2".equals(depositCarStatus)) {
                            ivUserDepositverfiyLeftpro.setImageResource(R.drawable.user_verfiy_leftpro);
                        } else {
                            ivUserDepositverfiyLeftpro.setImageResource(R.drawable.user_unverfiy_leftpro);
                        }

                        if (!"0".equals(response.body().getAttachment().getIdentityPositivePicture()) && response.body().getAttachment().getIdentityPositivePicture() != null) {

                            ImageLoader.getInstance().displayImage(getApplicationContext(),
                                    ((MyApplication) getApplication()).getImageUrl() + response.body().getAttachment().getIdentityPositivePicture(), iv_idcard_front);
                            flag0 = true;
                            submitType = 0;
                            picKeyArray[submitType] = response.body().getAttachment().getIdentityPositivePicture();

                            Glide.with(getApplicationContext()).load(((MyApplication) MyApplication.getInstance()).getImageUrl() + response.body().getAttachment().getIdentityPositivePicture()).asBitmap().into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(final Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {

                                    try {
                                        outputFile_idCard = FileUtil.getSaveIdCardFile(mContext);
                                        if (!outputFile_idCard.exists()) {
                                            outputFile_idCard.createNewFile();
                                        }
                                        FileOutputStream fileOutputStream = new FileOutputStream(outputFile_idCard);
                                        resource.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                                        fileOutputStream.close();
                                        if (null != outputFile_idCard) {
                                            recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, outputFile_idCard.getAbsolutePath());
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });

                        }
                        if (!"0".equals(response.body().getAttachment().getIdentityOppositePicture()) && response.body().getAttachment().getIdentityOppositePicture() != null) {

                            ImageLoader.getInstance().displayImage(getApplicationContext(),
                                    ((MyApplication) getApplication()).getImageUrl() + response.body().getAttachment().getIdentityOppositePicture(), iv_idcard_versa);
                            flag1 = true;
                            submitType = 1;
                            picKeyArray[submitType] = response.body().getAttachment().getIdentityOppositePicture();

                        }

                        if (!TextUtils.isEmpty(response.body().getAttachment().getSelfie()) && !"0".equals(response.body().getAttachment().getSelfie()) && response.body().getAttachment().getSelfie() != null) {

                            ImageLoader.getInstance().displayImage(getApplicationContext(),
                                    ((MyApplication) getApplication()).getImageUrl() + response.body().getAttachment().getSelfie(), iv_selfphoto);
                            flag2 = true;
                            submitType = 2;
                            picKeyArray[submitType] = response.body().getAttachment().getSelfie();

                            Glide.with(getApplicationContext()).load(((MyApplication) MyApplication.getInstance()).getImageUrl() + response.body().getAttachment().getSelfie()).asBitmap().into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(final Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {

                                    try {
                                        outputFile_self = FileUtil.getSaveZiPaiFile(mContext);
                                        if (!outputFile_self.exists()) {
                                            outputFile_self.createNewFile();
                                        }
                                        FileOutputStream fileOutputStream = new FileOutputStream(outputFile_self);
                                        resource.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                                        fileOutputStream.close();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }

                                }
                            });

                        }
                        if (!"0".equals(response.body().getAttachment().getLicensePicture()) && response.body().getAttachment().getLicensePicture() != null) {

                            ImageLoader.getInstance().displayImage(getApplicationContext(),
                                    ((MyApplication) getApplication()).getImageUrl() + response.body().getAttachment().getLicensePicture(), ivDriveQian);
                            flag3 = true;
                            submitType = 3;
                            picKeyArray[submitType] = response.body().getAttachment().getLicensePicture();

                            Glide.with(getApplicationContext()).load(((MyApplication) MyApplication.getInstance()).getImageUrl() + response.body().getAttachment().getLicensePicture()).asBitmap().into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(final Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {

                                    try {
                                        outputFile_drive = FileUtil.getSaveJiaZhaoFile(mContext);
                                        if (!outputFile_drive.exists()) {
                                            outputFile_drive.createNewFile();
                                        }
                                        FileOutputStream fileOutputStream = new FileOutputStream(outputFile_drive);
                                        resource.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                                        fileOutputStream.close();
                                        if (null != outputFile_drive) {
                                            recDrivingLicense(outputFile_drive.getAbsolutePath());
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }

                                }
                            });

                        }
                        if (!"0".equals(response.body().getAttachment().getLicensePictureCopy()) && response.body().getAttachment().getLicensePictureCopy() != null) {

                            ImageLoader.getInstance().displayImage(getApplicationContext(),
                                    ((MyApplication) getApplication()).getImageUrl() + response.body().getAttachment().getLicensePictureCopy(), iv_drive_hou);
                            flag4 = true;
                            submitType = 4;
                            picKeyArray[submitType] = response.body().getAttachment().getLicensePictureCopy();

                        }


                        if (flag0 && flag1 && flag2 && flag3 && flag4) {
                            flag = true;
                            checkInfo();
                        }

                    } else {
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<QualificationBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                Logger.d("neterror", "008");
            }
        });
    }

    @Override
    public void onDestroy() {
        // 释放本地质量控制模型
        CameraNativeHelper.release();
        super.onDestroy();
        if (pics != null && pics.size() != 0) {
            for (int i = 0; i < pics.size(); i++) {
                SDCardUtils.removeFileFromSDCard(pics.get(i));
            }
        }
    }

    /**
     * 做一些收尾工作，把这些工作从onDestory中移到正确的位置
     * 可以以防止新的activity启动后被调用
     */
    private void doClear() {
        CameraThreadPool.cancelAutoFocusTimer();
        IDcardQualityProcess.getInstance().releaseModel();
    }

    @Override
    public void onBackPressed() {
        AppManager.getAppManager().finishActivity();
    }

    /**
     * 公安接口合并在线活体，调用公安验证接口进行最后的核身比对；公安权限需要在官网控制台提交工单开启
     * 接口地址：https://aip.baidubce.com/rest/2.0/face/v2/person/verify
     * 入参为「姓名」「身份证号」「bestimage」
     * ext_fields 扩展功能。如 faceliveness 表示返回活体值, qualities 表示返回质检测结果
     * quality string 判断质 是否达标。“use” 表示做质 控制,质  好的照 会 直接拒绝
     * faceliveness string 判断活体值是否达标。 use 表示做活体控制,低于活体阈值的 照 会直接拒绝
     * quality_conf和faceliveness_conf 用于指定阈值，超过此分数才调用公安验证，
     *
     * @param filePath
     */
    private void policeVerify(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            policeDegree = "0";
            confirmUserInfor();
            return;
        }
        File file = new File(filePath);
        if (!file.exists()) {
            policeDegree = "0";
            confirmUserInfor();
            return;
        }
        APIService.getInstance().policeVerify(name, num, filePath, new
                PoliceOnResultListener<LivenessVsIdcardResult>() {
                    @Override
                    public void onResult(LivenessVsIdcardResult result) {
                        DecimalFormat df = new DecimalFormat("0.0000");
                        if (result != null) {
                            policeDegree = df.format(result.getScore() * 100);
                            Logger.d("RENLIAN", "核身成功：");
                        } else {
                            policeDegree = "0";
                            Logger.d("RENLIAN", "核身失败");
                        }
                        confirmUserInfor();
                    }

                    @Override
                    public void onError(FaceException error) {
                        // TODO 错误处理
                        policeDegree = "0";
                        confirmUserInfor();
                        // 如返回错误码为：216600，则核身失败，提示信息为：身份证号码错误
                        // 如返回错误码为：216601，则核身失败，提示信息为：身份证号码与姓名不匹配
                        Logger.d("RENLIAN", "核身失败：" + error.getErrorMessage());

                    }
                });
    }

    private void recDrivingLicense(String filePath) {
        OcrRequestParams param = new OcrRequestParams();
        param.setImageFile(new File(filePath));
        OCR.getInstance(this).recognizeDrivingLicense(param, new OnResultListener<OcrResponseResult>() {
            @Override
            public void onResult(OcrResponseResult result) {
                //listener.onResult(result.getJsonRes());
                Logger.d("OCRJSON", result.getJsonRes());
                String ocr = result.getJsonRes();
                drivingCard = ocr + "";
                Gson gson = new Gson();
                String name = gson.fromJson(ocr, DrvingBean.class).getWords_result().get姓名().getWords();
                SPUtils.getInstance(mContext).putStringValue(SPKey.DRIVING_NAME, name);
            }

            @Override
            public void onError(OCRError error) {
                //listener.onResult(error.getMessage());
                Logger.d("CameraActivity_OCR_FAIL", error.getMessage());
            }
        });
    }
}

